package com.deyou.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.deyou.Constants;
import com.deyou.R;
import com.deyou.adapter.HomePageRecommendAdapter;
import com.deyou.base.BaseActivity;
import com.deyou.callback.ServerApi;
import com.deyou.model.LandloadInfoBean;
import com.deyou.model.LzyResponse;
import com.deyou.util.AESUtil;
import com.deyou.util.GlideImageLoader;
import com.deyou.util.SPUtils;
import com.deyou.util.Urls;
import com.deyou.widget.CircleImageView;
import com.deyou.widget.RxTextRoundProgressBar;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class LandloadDetailActivity extends BaseActivity {

    @BindView(R.id.satisfaction_bar)
    RxTextRoundProgressBar satisfactionBar;
    @BindView(R.id.recovery_rate_bar)
    RxTextRoundProgressBar recoveryRateBar;
    @BindView(R.id.tv_landlord_hobby)
    TextView tvLandlordHobby;
    @BindView(R.id.tv_landlord_intro)
    TextView tvLandlordIntro;
    @BindView(R.id.tv_comments_count)
    TextView tvCommentsCount;
    @BindView(R.id.star_layout)
    LinearLayout starLayout;
    @BindView(R.id.iv_house_appraiser)
    CircleImageView ivHouseAppraiser;
    @BindView(R.id.tv_appraiser)
    TextView tvAppraiser;
    @BindView(R.id.tv_appraise_time)
    TextView tvAppraiseTime;
    @BindView(R.id.tv_comment_content)
    TextView tvCommentContent;
    @BindView(R.id.comment_imgs_layout)
    LinearLayout commentImgsLayout;
    @BindView(R.id.tv_all_comments)
    TextView tvAllComments;
    @BindView(R.id.landlord_comments_layout)
    LinearLayout landlordCommentsLayout;
    @BindView(R.id.ic_mobile_label)
    ImageView icMobileLabel;
    @BindView(R.id.ic_idcard_label)
    ImageView icIdcardLabel;
    @BindView(R.id.ic_zhima_label)
    ImageView icZhimaLabel;
    @BindView(R.id.landlord_house_recyclerview)
    RecyclerView landlordHouseRecyclerview;
    @BindView(R.id.landlord_houses_layout)
    LinearLayout landlordHousesLayout;
    @BindView(R.id.ic_landlord)
    CircleImageView icLandlord;
    @BindView(R.id.tv_landlord_name)
    TextView tvLandlordName;
    @BindView(R.id.tv_landlord_location)
    TextView tvLandlordLocation;
    @BindView(R.id.ic_landlord_sex)
    ImageView icLandlordSex;
    @BindView(R.id.iv_left_back)
    ImageView ivLeftBack;
    @BindView(R.id.tv_mid_title)
    TextView tvMidTitle;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.iv_right)
    ImageView ivRight;
    @BindView(R.id.title_view)
    RelativeLayout titleView;
    @BindView(R.id.header_layout)
    RelativeLayout headerLayout;

    private LandloadInfoBean landloadInfo;
    private HomePageRecommendAdapter recommendAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_landload_detail);
        ButterKnife.bind(this);
        initView();
        getLandloadData();
    }

    private void initView() {
        tvMidTitle.setText("房东主页");
        recommendAdapter = new HomePageRecommendAdapter(this);
    }

    private void getLandloadData() {
        JSONObject object = new JSONObject();
        try {
            object.put("userId", SPUtils.getStringByKey(this, Constants.UserId));
            String paramsJson = object.toString();
            Type type = new TypeToken<LzyResponse<LandloadInfoBean>>() {
            }.getType();
            ServerApi.<LzyResponse<LandloadInfoBean>>getData(type, Urls.getLandLoadHomePage, "", AESUtil.encrypt(paramsJson))
                    .subscribeOn(Schedulers.io())
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(@NonNull Disposable disposable) throws Exception {
                            showLoading("获取房东信息中...");
                        }
                    }).map(new Function<LzyResponse<LandloadInfoBean>, LandloadInfoBean>() {
                @Override
                public LandloadInfoBean apply(@NonNull LzyResponse<LandloadInfoBean> landloadInfo) throws Exception {
                    return landloadInfo.data;
                }
            }).observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<LandloadInfoBean>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {
                            addDisposable(d);
                        }

                        @Override
                        public void onNext(@NonNull LandloadInfoBean bean) {
                            landloadInfo = bean;
                            handler.sendEmptyMessage(1);
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {
                            e.printStackTrace();            //请求失败
                            dismissLoading();
                        }

                        @Override
                        public void onComplete() {
                            dismissLoading();
                        }
                    });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    fillLandloadData();
                    break;
            }
        }
    };

    private void fillLandloadData(){
        if (null != landloadInfo){
            starLayout.removeAllViews();
            for (int i = 0; i < 5; i++) {
                ImageView ivStar = new ImageView(this);
                if (i < landloadInfo.evaluate.evaluateStar) {
                    ivStar.setImageResource(R.drawable.ic_star_sel);
                } else {
                    ivStar.setImageResource(R.drawable.ic_star_nor);
                }
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(44, 60);
                ivStar.setLayoutParams(params);
                ivStar.setPadding(5, 0, 5, 0);
                starLayout.addView(ivStar);
            }
            if (!TextUtils.isEmpty(landloadInfo.userPic))
                new GlideImageLoader().displayImage(this, Urls.UserImageBaseUrl + landloadInfo.userPic, icLandlord);
            else
                new GlideImageLoader().displayImage(this, R.drawable.ic_default_avatar2, icLandlord);
            tvLandlordName.setText(landloadInfo.userNickname);
            satisfactionBar.setProgress(landloadInfo.userSatisfaction);
            satisfactionBar.setProgressText(landloadInfo.userSatisfaction + "%");
            recoveryRateBar.setProgress(landloadInfo.userRecoveryrate);
            recoveryRateBar.setProgressText(landloadInfo.userRecoveryrate + "%");
            tvLandlordHobby.setText(landloadInfo.userHobby);
            tvLandlordIntro.setText(landloadInfo.userIntroduction);
            if (!TextUtils.isEmpty(landloadInfo.userPhone))
                icMobileLabel.setImageResource(R.drawable.ic_finished_landlord_info);
            else
                icMobileLabel.setImageResource(R.drawable.ic_unfinish_landlord_info);
            if (!TextUtils.isEmpty(landloadInfo.userCard))
                icIdcardLabel.setImageResource(R.drawable.ic_finished_landlord_info);
            else
                icIdcardLabel.setImageResource(R.drawable.ic_unfinish_landlord_info);
            if (!TextUtils.isEmpty(landloadInfo.userSesameCredit))
                icZhimaLabel.setImageResource(R.drawable.ic_finished_landlord_info);
            else
                icZhimaLabel.setImageResource(R.drawable.ic_unfinish_landlord_info);
            if (null != landloadInfo.houseList && landloadInfo.houseList.size() > 0){
                landlordHousesLayout.setVisibility(View.VISIBLE);
                landlordHouseRecyclerview.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
                recommendAdapter.setData(landloadInfo.houseList);
                landlordHouseRecyclerview.setAdapter(recommendAdapter);
            } else {
                landlordHousesLayout.setVisibility(View.GONE);
            }
        }
    }

    @OnClick(R.id.iv_left_back)
    public void onViewClicked() {
        finish();
    }
}

